package com.fzy.core.system.action;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.fzy.core.system.entity.EntityWrapper;
import com.fzy.core.system.entity.PropertyWrapper;
import com.fzy.core.system.service.DbService;
import com.fzy.core.utils.DateUtils;
import com.fzy.core.webwork.BaseAction;
import com.fzy.core.webwork.MyValidationAware;
import com.opensymphony.xwork.ModelDriven;
import com.opensymphony.xwork.Preparable;

public class CommonInputAction extends BaseAction implements
		MyValidationAware, Preparable, ModelDriven {

	private static final long serialVersionUID = 1536502550176168099L;
	String errorDispatch;
	Map m;
	EntityWrapper entityWrapper;
	DbService dbService;
	public void prepare() throws Exception {
		errorDispatch = "redirect:list.do";
		entityWrapper = dbService.initEntityWrapper();

		m = dbService.getEntityData(entityWrapper, request);
		if(m == null) m = new HashMap();
		else{
			for (Iterator iterator = entityWrapper.getProperties().iterator(); iterator.hasNext();) {
				PropertyWrapper pw = (PropertyWrapper) iterator.next();
				String fieldName = pw.getColumnName();
				Object value = m.get(fieldName);
				String pattern = pw.getDateFormatShow();
//				if(PropertyWrapper.JAVA_DATE.equals(pw.getJavaType())){
//					if(value != null){
//						m.put(fieldName, DateUtils.formatSafely((Date)value, pattern));
//					}
//				}else 
				if(pw.getHasDateFormat() && pw.getHasDateFormatShow()){
					if(value != null){
						m.put(fieldName, DateUtils.parseDateSafely((String)value, pw.getData().getDateFormat(), pattern));
					}
				}
			}
		}
	}

	public void validate() {

	}

	public String execute() throws Exception {
		return "dispatcher:/WEB-INF/jsp/core/system/common-input.jsp";
	}

	public String getErrorDispatch() {
		return errorDispatch;
	}

	public EntityWrapper getEntityWrapper() {
		return entityWrapper;
	}

	public void setDbService(DbService dbService) {
		this.dbService = dbService;
	}

	public Object getModel() {
		return m;
	}

	public Map getM() {
		return m;
	}

}
